import React, { useCallback, useRef, useState } from 'react';
import ContractCall from './contractCall/ContractCall';
import ContractCompile from './contractCompile/ContractCompile';
import ContractDebug from './contractDebug/ContractDebug';
import ContractDeploy from './contractDeploy/ContractDeploy';
import FileTree from './fileTree';
import fold from '@ide/static/svgs/fold.svg';
import useAppStore from '@ide/store';
import { Button, message } from 'tea-component';
import { importFiles } from '@/api';
import { useIdeStore } from 'ide-plugin';
export default function SideTab() {
  const [creareContract, setcreareContract] = useState<string>('');
  const {
    leftCurrentTab, setModalStatus, setEditHiddenContractsVisible, setNewnewContractVisible,
    activeTreeNode, getFiles, server
  } = useAppStore();
  const {
    setIsHideLeftContent
  } = useIdeStore();

  const fileInput = useRef<HTMLInputElement | null>(null);
  const triggerSelectFile = useCallback(() => {
    fileInput.current?.click();
  }, []);
  const importFile = useCallback(() => {
    if(!fileInput.current){
      return;
    }
    const files = fileInput.current.files;
    if (files && files.length) {
      const MAXFILESIZE = 2 * 1024 * 1024;
      if (files.length > 20) {
        setModalStatus({
          modalShow: true,
          modalContent: '上传文件一次最多上传20个。'
        });
        return false;
      }
      for (let len = 0; len < files.length; len++) {
        const file = files[len];
        if (file.size > MAXFILESIZE) {
          setModalStatus({
            modalShow: true,
            modalContent: '单个文件大小不能超过2M。'
          });
          return false;
        }
      }
      let path = '';
      if (activeTreeNode?.path) {
        const reg = /(\/[^/]+\.[^.]+)$/;
        if (reg.test(activeTreeNode.path)) {
          path = activeTreeNode.path.replace(reg, '');
        } else {
          path = activeTreeNode.path;
        }
      }
      if (!path) {
        message.warning({
          content:'请选择文件上传目标位置'
        })
        return;
      }

      const fd = new FormData();
      for (let i = 0; i < files.length; i++) {
        fd.append('fileupload', files[i]);
      }
      fd.append('path', path);

      importFiles(fd).then(() => {
        getFiles();
        if(fileInput.current) {
          fileInput.current.value = '';
        }
      });
      // $.ajax({
      //   url: '/file/import',
      //   type: 'POST',
      //   data: fd,
      //   contentType: false,
      //   processData: false,
      //   success: function (result) {
      //     if (result.code === -1) {
      //       $('#dialogAlert').dialog('open', result.msg)
      //     } else {
      //       $('.upload-files').val(null)
      //       // tree.init();
      //     }
      //   },
      //   complete: function () {
      //     $('.disable-vdom').remove()
      //   }
      // })
    }
  }, [server, activeTreeNode]);
  const manageContract = useCallback(() => {
    setEditHiddenContractsVisible(true);
  }, []);
  // useEffect(() => {
  //   if (leftCurrentTab === 'contractCompile') {
  //     window.location.href = 'https://192.168.3.170:17766/contract/editing';
  //   }
  // }, [leftCurrentTab]);
  return <>
    <div className='nav_header'>
      <div className='nav_options'>
        {leftCurrentTab === 'fileTree' && <>
          <Button onClick={()=> {
            const c = `contract_${new Date().getTime()}`
            setNewnewContractVisible(c)
          }} type="primary">创建</Button>
          <Button onClick={triggerSelectFile} type="primary">导入</Button>
          <Button onClick={manageContract} type="primary">管理</Button>
          {/* <img title='导入文件' onClick={triggerSelectFile} className='nav_import' src={addfile} /> */}
        </>}
        <input
          ref={(ref) => (fileInput.current = ref)}
          type="file"
          onChange={importFile}
          multiple
          accept={['.go', '.txt', '.md', '.mod', '.sum', '.java', '.sol', '.crt', '.key', '.yml'].join(',')}
          className="upload-files"
          style={{ width: 0, height: 0, opacity: 0 }} />
      </div>
      <img src={fold} className='nav_action' onClick={() => setIsHideLeftContent(true)} />
    </div>
    <div className='ide_nav_c'>
      <FileTree creareContract={creareContract} style={{ display: leftCurrentTab === 'fileTree' ? 'block' : 'none' }}/>
      <ContractDebug style={{ display: leftCurrentTab === 'contractDebug' ? 'block' : 'none' }} />
      <ContractCompile style={{ display: leftCurrentTab === 'contractCompile' ? 'block' : 'none' }} />
      <ContractDeploy style={{ display: leftCurrentTab === 'contractDeploy' ? 'block' : 'none' }} />
      <ContractCall style={{ display: leftCurrentTab === 'contractCall' ? 'block' : 'none' }} />
    </div>
  </>;
}
